#include <string.h>
#include <ctype.h>
#include "web_log.h"
#include "web_internal.h"
#include <fcgiapp.h>

void web_respone_err(FCGX_Request *req,const char *err_str) 
{
    if (NULL == req || NULL == err_str) {
        return;
    }
    
    // 创建简单的错误 JSON 响应
    char json_response[128];
    snprintf(json_response, sizeof(json_response), "{\"error\":\"%s\"}", err_str);
    int content_length = strlen(json_response);
    
    FCGX_FPrintF(req->out, "Status: %s\r\n"
                "Content-Type: application/json\r\n"
                "Content-Length: %d\r\n"
                "\r\n"
                "%s", err_str, content_length, json_response);
}

void web_respone_json(FCGX_Request *req,struct json_object *obj)
{
    const char *json_str = NULL;
    if (NULL == req || NULL == obj) {
        return;
    }

    json_str = json_object_to_json_string(obj);

    if (NULL != json_str) {
        FCGX_FPrintF(req->out, "Status: 200 OK\r\n"
                    "Content-Type: application/json\r\n"
                    "Content-Length: %d\r\n"
                    "\r\n"
                    "%s", strlen(json_str), json_str);
    } else {
        web_respone_err(req,WEB_STATUE_STR_400);
    }

}   


// URL解码函数
static void url_decode(char *dst, const char *src, int len)
{
    char a, b;
    int i, j;
    
    for (i = 0, j = 0; src[i] && j < len - 1; i++, j++) {
        if (src[i] == '%' && isxdigit((unsigned char)src[i+1]) && isxdigit((unsigned char)src[i+2])) {
            a = src[i+1];
            b = src[i+2];
            
            if (a >= 'a') a -= 'a' - 'A';
            if (a >= 'A') a -= ('A' - 10);
            else a -= '0';
            
            if (b >= 'a') b -= 'a' - 'A';
            if (b >= 'A') b -= ('A' - 10);
            else b -= '0';
            
            dst[j] = 16 * a + b;
            i += 2;
        } else if (src[i] == '+') {
            dst[j] = ' ';
        } else {
            dst[j] = src[i];
        }
    }
    
    dst[j] = '\0';
}

void extract_url_param(char *url, const char *pname, char* pvalue, int len) 
{
    char *str = NULL;
    char *p = NULL;
    char temp_value[QUERY_STRING_VALUE_MAX_LEN];
    int namelen = 0;
    int valuelen = 0;
    
    if (NULL == url || NULL == pname || NULL == pvalue) {
        return;
    }

    namelen = strlen(pname);

    // 查找参数名
    str = strstr(url, pname);
    if (NULL == str) {
        return;
    }
    
    // 移动到参数值的开始位置（跳过参数名和等号）
    str += namelen;
    str++;

    // 查找参数值的结束位置（&或字符串结束）
    p = str;
    while((*p != '&') && (*p != '\0')) {
        p++;
    }
    valuelen = (int)(p - str);

    if (valuelen > len - 1) {
        valuelen = len - 1;
        log_error("extract query param error: %s value too long", pname);
    }
    
    // 复制参数值到临时缓冲区
    memcpy(temp_value, str, valuelen);
    temp_value[valuelen] = '\0';
    
    // URL解码参数值
    url_decode(pvalue, temp_value, len);
}